 package com.gmrz.uaf.common;
 
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.nio.ByteOrder;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 
 public abstract class TLVType2
 {
   static final int TAG_SIZE = 2;
   static final int LENGTH_SIZE = 2;
   List<TLVSegment> tlvs;
 
   public TLVType2()
   {
     this.tlvs = Collections.synchronizedList(new ArrayList());
   }
 
   public void addTLVSegment(short tag, short length, byte[] data) {
     TLVSegment segment = new TLVSegment(tag, length, data);
     synchronized (this.tlvs) {
       this.tlvs.add(segment);
     }
   }
 
   public void addTLVSegment(short tag, byte[] data) {
     short length = (short)data.length;
     addTLVSegment(tag, length, data);
   }
 
   public byte[] getValueOfTag(short tag) {
     synchronized (this.tlvs) {
       for (TLVSegment seg : this.tlvs) {
         if (tag == seg.tag) {
           return seg.data;
         }
       }
     }
     return null;
   }
 
   public byte[] getTLVBytes() throws IOException {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     synchronized (this.tlvs) {
       Iterator itr = this.tlvs.iterator();
       while (itr.hasNext()) {
         TLVSegment seg = (TLVSegment)itr.next();
         ByteBuffer bb = ByteBuffer.wrap(new byte[seg.length + 2 + 2]).order(ByteOrder.LITTLE_ENDIAN);
         bb.putShort(seg.tag).putShort(seg.length).put(seg.data == null ? new byte[0] : seg.data);
         baos.write(bb.array());
       }
     }
     return baos.toByteArray();
   }
 
   private static class TLVSegment {
     short tag;
     short length;
     byte[] data;
 
     TLVSegment(short tag, short length, byte[] data) {
       this.tag = tag;
       this.length = length;
       this.data = data;
     }
   }
 }
